package com.semagsoft.droidbrowse;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.app.Activity;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView engine = (WebView) findViewById(R.id.webView);
        engine.getSettings().setJavaScriptEnabled(true);
        engine.getSettings().setBuiltInZoomControls(true);
        engine.requestFocus();
        if (savedInstanceState == null)
        {
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
            String homepage = sharedPref.getString(SettingsActivity.HOMEPAGE, "Settings_HomePage");
            if (homepage.equals("Settings_HomePage")) {
                nav("http://semagsoft.com/AndroidHome");
            }
            else {
                nav(homepage);
            }
        }
        final Activity activity = this;
        engine.setWebChromeClient(new android.webkit.WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress != 100) {
                    setPageTitle("Loading... " + progress + "%");
                }
            }
        });
        engine.setWebViewClient(new android.webkit.WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                android.widget.Toast.makeText(activity, "Oh no! " + description, android.widget.Toast.LENGTH_SHORT).show();
            }
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                nav(url);
                return false;
            }
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                android.widget.TextView titlebar = (android.widget.TextView)findViewById(R.id.urlBox);
                WebView engine = (WebView) findViewById(R.id.webView);
                titlebar.setText(url);
                setPageTitle("Loading...");
                if (engine.canGoBack()) {
                    android.widget.ImageButton back = (android.widget.ImageButton) findViewById(R.id.backButton);
                    back.setVisibility(View.VISIBLE);
                }
                else {
                    android.widget.ImageButton back = (android.widget.ImageButton) findViewById(R.id.backButton);
                    back.setVisibility(View.GONE);
                }
                if (engine.canGoForward()) {
                    android.widget.ImageButton forward = (android.widget.ImageButton) findViewById(R.id.forwardButton);
                    forward.setVisibility(View.VISIBLE);
                }
                else {
                    android.widget.ImageButton forward = (android.widget.ImageButton) findViewById(R.id.forwardButton);
                    forward.setVisibility(View.GONE);
                }
            }
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                android.widget.TextView titlebar = (android.widget.TextView)findViewById(R.id.urlBox);
                WebView engine = (WebView) findViewById(R.id.webView);
                setPageTitle(engine.getTitle());
                findViewById(R.id.navBar).setVisibility(view.GONE);
                if (engine.canGoBack()) {
                    android.widget.ImageButton back = (android.widget.ImageButton) findViewById(R.id.backButton);
                    back.setVisibility(View.VISIBLE);
                }
                else {
                    android.widget.ImageButton back = (android.widget.ImageButton) findViewById(R.id.backButton);
                    back.setVisibility(View.GONE);
                }
                if (engine.canGoForward()) {
                    android.widget.ImageButton forward = (android.widget.ImageButton) findViewById(R.id.forwardButton);
                    forward.setVisibility(View.VISIBLE);
                }
                else {
                    android.widget.ImageButton forward = (android.widget.ImageButton) findViewById(R.id.forwardButton);
                    forward.setVisibility(View.GONE);
                }
            }
        });

        android.widget.ImageButton backbutton = (android.widget.ImageButton) findViewById(R.id.backButton);
        backbutton.setOnClickListener(new android.view.View.OnClickListener() {
            public void onClick(android.view.View v) {
                WebView engine = (WebView) findViewById(R.id.webView);
                engine.goBack();
            }
        });
        android.widget.ImageButton forwardbutton = (android.widget.ImageButton) findViewById(R.id.forwardButton);
        forwardbutton.setOnClickListener(new android.view.View.OnClickListener() {
            public void onClick(android.view.View v) {
                WebView engine = (WebView) findViewById(R.id.webView);
                engine.goForward();
            }
        });
        android.widget.EditText editText = (android.widget.EditText) findViewById(R.id.urlBox);
        editText.setOnEditorActionListener(new android.widget.TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(android.widget.TextView v, int actionId, android.view.KeyEvent event) {
                boolean handled = true;
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    android.widget.TextView titlebar = (android.widget.TextView)findViewById(R.id.urlBox);
                    WebView engine = (WebView) findViewById(R.id.webView);
                    engine.requestFocus();
                    nav(titlebar.getText().toString());
                    InputMethodManager inputManager = (InputMethodManager)
                            getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return handled;
            }
        });
        android.widget.ImageButton gobutton = (android.widget.ImageButton) findViewById(R.id.goButton);
        gobutton.setOnClickListener(new android.view.View.OnClickListener() {
            public void onClick(android.view.View v) {
                android.widget.TextView titlebar = (android.widget.TextView)findViewById(R.id.urlBox);
                WebView engine = (WebView) findViewById(R.id.webView);
                engine.requestFocus();
                nav(titlebar.getText().toString());
                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        WebView engine = (WebView) findViewById(R.id.webView);
        if ((keyCode == KeyEvent.KEYCODE_BACK) && engine.canGoBack()) {
            engine.goBack();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            if (findViewById(R.id.navBar).getVisibility() == View.VISIBLE) {
                findViewById(R.id.navBar).setVisibility(View.GONE);
                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                findViewById(R.id.navBar).setVisibility(android.view.View.VISIBLE);
                this.openOptionsMenu();
            }
            return true;
        }
        else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
            String searchEngine = sharedPref.getString(SettingsActivity.SEARCHENGINE, "Settings_SearchEngine");
            if (searchEngine.equals(("0"))) {
                nav("bing.com");
            }
            else {
                nav("google.com");
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void setPageTitle(String title) {
        this.setTitle(title);
    }

    public void nav(String url) {
        android.widget.TextView titlebar = (android.widget.TextView)findViewById(R.id.urlBox);
        WebView engine = (WebView) findViewById(R.id.webView);
        if (url.startsWith("http://") || url.startsWith("https://")) {
            engine.loadUrl(url);
        }
        else if (url.startsWith("about:")) {
            if (url.equals("about:blank")) {
                engine.loadUrl("");
                setPageTitle("Blank Page");
            }
            else if (url.equals("about:home")) {
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                String homepage = sharedPref.getString(SettingsActivity.HOMEPAGE, "Settings_HomePage");
                if (homepage.equals("Settings_HomePage")) {
                    engine.loadUrl("http://semagsoft.com/AndroidHome");
                }
                else {
                    engine.loadUrl(homepage);
                }
            }
            else {
                engine.loadUrl("http://" + url);
            }
        }
        else {
            engine.loadUrl("http://" + url);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        WebView engine = (WebView) findViewById(R.id.webView);
        engine.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onSaveInstanceState(savedInstanceState);
        WebView engine = (WebView) findViewById(R.id.webView);
        engine.restoreState(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                String searchEngine = sharedPref.getString(SettingsActivity.SEARCHENGINE, "Settings_SearchEngine");
                if (searchEngine.equals(("0"))) {
                    nav("bing.com");
                }
                else {
                    nav("google.com");
                }
                return true;
            case R.id.action_settings:
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            case R.id.action_about:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.app_name);
                builder.setIcon(R.drawable.ic_launcher);
                String sVersionName = null;
                try {
                    PackageInfo pinfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
                    sVersionName = pinfo.versionName;
                }
                catch ( PackageManager.NameNotFoundException e )
                {
                    System.err.println(">>>>" + e.getMessage() );
                    e.printStackTrace();
                }
                builder.setMessage("Version: " + sVersionName + "\nCopyright \u00a9 Semagsoft 2013");
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            case R.id.action_exit:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
}